package com.virtualperson.util;

import com.virtualperson.exception.VideoValidationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import java.net.URL;
import java.util.regex.Pattern;
import java.net.HttpURLConnection;

@Slf4j
public class VideoValidationUtil {
    // 支持的图片格式
    private static final Pattern IMAGE_URL_PATTERN = 
        Pattern.compile("^https?://.*\\.(jpg|jpeg|png|bmp|webp)$", Pattern.CASE_INSENSITIVE);
    
    // 支持的音频格式
    private static final Pattern AUDIO_URL_PATTERN = 
        Pattern.compile("^https?://.*\\.(wav|mp3)$", Pattern.CASE_INSENSITIVE);
    
    // 文件大小限制（字节）
    private static final long MAX_IMAGE_SIZE = 10 * 1024 * 1024;  // 10MB
    private static final long MAX_AUDIO_SIZE = 15 * 1024 * 1024;  // 15MB
    
    // 音频时长限制（秒）
    private static final float MIN_AUDIO_DURATION = 1.0f;  // 1秒
    private static final float MAX_AUDIO_DURATION = 300.0f;  // 5分钟
    
    // 图片尺寸限制
    private static final int MAX_IMAGE_DIMENSION = 4096;  // 最大边长
    private static final double MAX_ASPECT_RATIO = 2.0;   // 最大宽高比

    public static class VideoErrorCode {
        public static final String UNSUPPORTED_FILE_FORMAT = "InvalidParameter.UnsupportedFileFormat";
        public static final String INPUT_DOWNLOAD_FAILED = "InvalidParameter.InputDownloadFailed";
        public static final String IMAGE_SIZE_ERROR = "InvalidImage.ImageSize";
        public static final String AUDIO_LENGTH_ERROR = "InvalidFile.AudioLengthError";
        public static final String NO_HUMAN_FACE = "InvalidImage.NoHumanFace";
        public static final String PARAMETER_OUT_OF_DEFINITION = "InvalidParamter.OutOfDefinition";
        public static final String ALGO_ERROR = "InternalError.Algo";
        public static final String UPLOAD_ERROR = "InternalError.Upload";
    }

    public static String getErrorMessage(String errorCode) {
        switch (errorCode) {
            case VideoErrorCode.UNSUPPORTED_FILE_FORMAT:
                return "音频或图片格式不支持。音频支持格式mp3, wav, aac; 图片支持格式jpg, jpeg, png, bmp, webp。";
            case VideoErrorCode.INPUT_DOWNLOAD_FAILED:
                return "输入文件下载失败";
            case VideoErrorCode.IMAGE_SIZE_ERROR:
                return "图片大小超出限制。要求图片长宽比例不大于2，且最长边不大于4096。";
            case VideoErrorCode.AUDIO_LENGTH_ERROR:
                return "音频长度不符合要求（应在[1, 300]秒范围内）";
            case VideoErrorCode.NO_HUMAN_FACE:
                return "未检测到人脸";
            case VideoErrorCode.PARAMETER_OUT_OF_DEFINITION:
                return "参数类型或值不符合要求";
            case VideoErrorCode.ALGO_ERROR:
                return "算法运行时发生错误";
            case VideoErrorCode.UPLOAD_ERROR:
                return "生成结果上传失败";
            default:
                return "未知错误";
        }
    }

    public static void validateImage(String imageUrl) {
        if (!StringUtils.hasText(imageUrl)) {
            throw new VideoValidationException("图片URL不能为空");
        }

        // 验证URL格式
        try {
            new URL(imageUrl);
        } catch (Exception e) {
            throw new VideoValidationException("图片URL格式不正确");
        }

        // 验证图片格式
        if (!IMAGE_URL_PATTERN.matcher(imageUrl).matches()) {
            throw new VideoValidationException("图片URL必须是jpg、jpeg、png、bmp或webp格式");
        }

        // 验证图片大小
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(imageUrl).openConnection();
            connection.setRequestMethod("HEAD");
            
            // 检查文件大小
            long fileSize = connection.getContentLengthLong();
            if (fileSize > MAX_IMAGE_SIZE) {
                throw new VideoValidationException("图片文件大小不能超过10MB");
            }
            
            // 检查HTTP状态码
            int responseCode = connection.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_OK) {
                throw new VideoValidationException("图片URL无法访问，HTTP状态码: " + responseCode);
            }
            
        } catch (Exception e) {
            throw new VideoValidationException("验证图片URL失败: " + e.getMessage());
        }
    }

    public static void validateAudio(String audioUrl) {
        if (!StringUtils.hasText(audioUrl)) {
            throw new VideoValidationException("音频URL不能为空");
        }

        // 验证URL格式
        try {
            new URL(audioUrl);
        } catch (Exception e) {
            throw new VideoValidationException("音频URL格式不正确");
        }

        // 验证音频格式
        if (!AUDIO_URL_PATTERN.matcher(audioUrl).matches()) {
            throw new VideoValidationException("音频URL必须是mp3或wav格式");
        }

        // 验证音频大小
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(audioUrl).openConnection();
            connection.setRequestMethod("HEAD");
            
            // 检查文件大小
            long fileSize = connection.getContentLengthLong();
            if (fileSize > MAX_AUDIO_SIZE) {
                throw new VideoValidationException("音频文件大小不能超过15MB");
            }
            
            // 检查HTTP状态码
            int responseCode = connection.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_OK) {
                throw new VideoValidationException("音频URL无法访问，HTTP状态码: " + responseCode);
            }
            
        } catch (Exception e) {
            throw new VideoValidationException("验证音频URL失败: " + e.getMessage());
        }
    }
} 